import { useState, useEffect, useContext } from 'react';
import { NavBar, Image, InfiniteScroll, Grid } from "antd-mobile";
import { useHistory, useRouteMatch } from 'react-router-dom';
import moment from 'moment';

import { MySdkStoreContext } from '../../../context';

import './style.scss';

// 处理接口返回数据，按照YYYY年MM月进行分类
const formatResult = (rows) => {
  const map = {};

  rows.forEach(item => {
    const timeString = moment(item.timestamp).format('YYYY年MM月');
    if (map[timeString]) {
      map[timeString].push(item);
    } else {
      map[timeString] = [item];
    }
  });

  return map;
}

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [result, setResult] = useState({});
  const { params: { cid } } = useRouteMatch();
  const [pagination, setPagination] = useState({ pageIndex: 1 });

  // const handlerMulti = ImageViewer.Multi.show({
  //   iamges: [],
  //   defaultIndex: 0,
  // });

  // 处理”搜索“事件
  const handleSearch = async (pageIndex = 1) => {
    const { rows, current, totalItemCount, totalPage } = await mySdkStore.sdk.searchMessage({ resourceType: 'image', pageIndex, sessionIds: [cid] });
    const formattedResult = formatResult(rows);
    setResult(pageIndex === 1 ? formattedResult : {...result, ...formattedResult});

    setPagination({ pageIndex: current, totalItemCount, totalPage })
  }

  // 处理分页获取数据
  const getNextData = async () => {
    await handleSearch(pagination.pageIndex + 1);
  }

  useEffect(() => {
    handleSearch(1);
  }, []);

  return (
    <div className="searchMessagePicturePage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>图片&视频</NavBar>
      {Object.keys(result).map(timeString =>
        <div className="speratorBox">
          <div className="speratorTime">{timeString}</div>
          <Grid columns={4}>
            {result[timeString].map(item =>
             <Image src={item.msgContent?.pic} />
            )}
          </Grid>
        </div>
      )}
      <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
    </div>)
}